package com.example.musicplayer

import android.Manifest
import android.annotation.SuppressLint
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.media.MediaPlayer
import android.os.Build
import android.os.Bundle
import android.provider.MediaStore
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.SeekBar
import android.widget.TextView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.example.musicplayer.R.id.main
import java.io.IOException
import kotlin.concurrent.thread

class MainActivity : AppCompatActivity() {
    val TAG = "MainActivity"
    val mediaPlayer = MediaPlayer() // 音乐播放器实例
    val musicList: MutableList<String> = mutableListOf<String>() // 音乐路径列表
    val musicNameList: MutableList<String> = mutableListOf<String>() // 音乐名称列表
    var current = 0 // 当前播放的音乐索引
    var isPause = false // 是否暂停

    val Channel_ID = "my channel" // 通知频道 ID
    val Notification_ID = 1 // 通知 ID

    private lateinit var textViewMn: TextView // 显示音乐名称的 TextView
    private lateinit var textViewCount: TextView // 显示音乐数量的 TextView
    private lateinit var seekBar: SeekBar // 进度条

    @SuppressLint("ObsoleteSdkInt")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge() // 启用边缘到边缘的显示
        setContentView(R.layout.activity_main) // 设置布局文件

        // 初始化视图
        textViewMn = findViewById(R.id.textView_mn)
        textViewCount = findViewById(R.id.textView_count)
        seekBar = findViewById(R.id.seekBar)

        // 设置 MediaPlayer 完成播放的监听器
        mediaPlayer.setOnCompletionListener {
            current++
            if (current >= musicList.size) {
                current = 0
            }
            play() // 播放下一首音乐
        }

        // 设置 MediaPlayer 准备完成的监听器
        mediaPlayer.setOnPreparedListener {
            it.start() // 开始播放
            seekBar.max = mediaPlayer.duration // 设置进度条的最大值为音乐的持续时间
            updateSeekBar() // 更新进度条
        }

        // 设置窗口内边距
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        // 请求读取媒体文件的权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_MEDIA_AUDIO) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.READ_MEDIA_AUDIO), 0)
        } else {
            getMusicList() // 获取音乐列表
        }

        // 设置进度条的监听器
        seekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
                if (fromUser) {
                    mediaPlayer.seekTo(progress) // 用户拖动进度条时，调整播放进度
                }
            }

            override fun onStartTrackingTouch(seekBar: SeekBar) {}
            override fun onStopTrackingTouch(seekBar: SeekBar) {}
        })
    }

    // 更新进度条
    private fun updateSeekBar() {
        thread {
            while (mediaPlayer.isPlaying) {
                Thread.sleep(1000)
                runOnUiThread {
                    seekBar.progress = mediaPlayer.currentPosition // 更新进度条的当前进度
                }
            }
        }
    }

    // 播放按钮点击事件
    fun onPlay(v: View) {
        play() // 播放音乐
    }

    // 显示通知的方法
    fun NotificationFun() {
        val notificationManager =
            getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        val builder: Notification.Builder

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val notificationChannel =
                NotificationChannel(Channel_ID, "test", NotificationManager.IMPORTANCE_DEFAULT)
            notificationManager.createNotificationChannel(notificationChannel)
            builder = Notification.Builder(this, Channel_ID)
        } else {
            builder = Notification.Builder(this)
        }

        val intent = Intent(this, MainActivity::class.java)
        val pendingIntent = PendingIntent.getActivity(
            this,
            1,
            intent,
            PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
        )

        val notification = builder.setSmallIcon(R.drawable.ic_notification)
            .setContentTitle("Now Playing")
            .setContentText(musicNameList[current]) // 设置通知内容为当前播放的音乐名称
            .setContentIntent(pendingIntent)
            .setAutoCancel(true)
            .build()

        notificationManager.notify(Notification_ID, notification) // 显示通知
    }

    // 暂停按钮点击事件
    fun onPause(v: View) {
        if (isPause) {
            mediaPlayer.start() // 继续播放
            isPause = false
        } else {
            mediaPlayer.pause() // 暂停播放
            isPause = true
        }
    }

    // 停止按钮点击事件
    fun onStop(v: View) {
        mediaPlayer.stop() // 停止播放
    }

    // 下一首按钮点击事件
    fun onNext(v: View) {
        current++
        if (current >= musicList.size) {
            current = 0
        }
        play() // 播放下一首音乐
    }

    // 上一首按钮点击事件
    fun onPrev(v: View) {
        current--
        if (current < 0) {
            current = musicList.size - 1
        }
        play() // 播放上一首音乐
    }

    // 播放音乐
    fun play() {
        if (musicList.isEmpty()) return
        val path = musicList[current]
        try {
            mediaPlayer.reset()
            mediaPlayer.setDataSource(path) // 指定数据源
            mediaPlayer.prepareAsync() // 异步准备
            textViewMn.text = musicNameList[current] // 更新音乐名称
            textViewCount.text = "${current + 1}/${musicList.size}" // 更新音乐数量
        } catch (e: IOException) {
            e.printStackTrace()
        }
        NotificationFun() // 显示通知
    }

    // 请求权限结果回调
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == 0 && grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            getMusicList() // 获取音乐列表
        }
    }

    // 获取音乐列表
    private fun getMusicList() {
        val cursor = contentResolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null, null)
        if (cursor != null) {
            while (cursor.moveToNext()) {
                val dataIndex = cursor.getColumnIndex(MediaStore.Audio.Media.DATA)
                val titleIndex = cursor.getColumnIndex(MediaStore.Audio.Media.TITLE)
                if (dataIndex != -1 && titleIndex != -1) {
                    val musicPath = cursor.getString(dataIndex)
                    musicList.add(musicPath) // 添加音乐路径到列表
                    val musicName = cursor.getString(titleIndex)
                    musicNameList.add(musicName) // 添加音乐名称到列表
                    Log.d(TAG, "getMusicList(): $musicPath name: $musicName")
                }
            }
            cursor.close()
        }
    }

    // 销毁时释放 MediaPlayer
    override fun onDestroy() {
        super.onDestroy()
        mediaPlayer.release() // 释放 MediaPlayer 资源
    }
}